import Vue from 'vue'
import Vuex from 'vuex'
import router from '../router'

Vue.use(Vuex)

export default new Vuex.Store({

  //全局属性 
  state: {
    //用户数据
    user: {
      Roles: '',
      Token: '',
      UserId: 0,
      UserName: '',
      Exp: '',
      ImgPath:''
    },
    CId: 0,
    Count: 0,
    //菜单相关
    //选中的值
    tableTabsValue: '1'
    //选项卡 数据
    , tableTabs: []
  },

  //计算属性
  getters: {
  },

  //方法
  mutations: {
    setUser(state, payload) {
      sessionStorage.setItem('user', JSON.stringify(payload));
      state.user = JSON.parse(JSON.stringify(payload));
    },

    //菜单相关
    //添加选项卡
    addTab(state, menu) {
      //先判断当前选项卡 是否存在
      if (!state.tableTabs.some(v => v.name == menu.MenuID)) {
        state.tableTabs.push({
          title: menu.MenuName,
          name: menu.MenuID + '',
          icon: menu.Icon,
          viewUrl: menu.Url
        });
      }
      //切换选中
      state.tableTabsValue = menu.MenuID + '';

      //通过  tableTabsValue  当前选中选项卡获取 路由地址
      let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
      //切换路由

      //
      router.replace(viewUrl);

    }, 
    //移除选项卡
    removeTab(state, targetName) {
      let tabs = state.tableTabs;
      let activeName = state.tableTabsValue;
      //移除的选项卡是当前选中选项卡
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
            }
          }
        });
        //通过  tableTabsValue  当前选中选项卡获取 路由地址
        let viewUrl = state.tableTabs.filter(v => v.name == activeName)[0].viewUrl;
        //切换路由
        router.push(viewUrl);
      }
      state.tableTabsValue = activeName;
      //使用筛选移除
      state.tableTabs = tabs.filter(tab => tab.name !== targetName);
    }, 
    //点击选项卡切换
    clickTab(state) {
      //通过  tableTabsValue  当前选中选项卡获取 路由地址
      let viewUrl = state.tableTabs.filter(v => v.name == state.tableTabsValue)[0].viewUrl;
      //切换路由 
      if (location.pathname != viewUrl)
        router.push(viewUrl);
    }, 
    edittableTabsValue(state, value) {
      state.tableTabsValue = value;
    }
  },

  //方法
  actions: {
    //axios ajax 
    addCart(context) {
      //
      //context.commit('addCart',{});
    }
  },

  //模块 
  modules: {
  }
})
